<?php

namespace App\Model\Report;

use App\Model\Model;
use Hyperf\Database\Model\Builder;

class OppoDevice extends Model
{
    protected ?string $table = "oppo_device";

    public static function findDevice($appId, $oaid)
    {
        if (empty($oaid)) {
            return null;
        }

        return self::query()->where("app_id", $appId)
            ->where("oaid", $oaid)
            ->orderByDesc("id")
            ->first();
    }

    public static function findReportDevice($appId, $oaid, $dynamicColumn, $adPlanId)
    {
        if (empty($oaid)) {
            return null;
        }

        return self::query()->where("app_id", $appId)
            ->where("oaid", $oaid)
            ->where($dynamicColumn, 1)
            ->when($adPlanId, function (Builder $builder) use ($adPlanId) {
                $builder->where("ad_plan_id", $adPlanId);
            })
            ->orderByDesc("id")
            ->first();
    }

    public static function findReportAscribeDevice($appId, $oaid)
    {
        // 先找最新一条点击
        $lastDevice = self::findDevice($appId, $oaid);
        $lastDeviceAdPlanId = '';
        if ($lastDevice) {
            $lastDeviceAdPlanId = $lastDevice->ad_plan_id;
        }

        // 查询是否有激活状态为1的
        $device = self::findReportDevice($appId, $oaid, "activation_status", $lastDeviceAdPlanId);
        if ($device) {
            return $device;
        }

        // 没有的话就找关键行为过的
        $device = self::findReportDevice($appId, $oaid, "register_status", $lastDeviceAdPlanId);
        if ($device) {
            return $device;
        }

        // 关键行为也没有，就找最新一条
        return $lastDevice;
    }
}